package com.cheng.shiro.realm;

import com.cheng.dao.UserDao;
import com.cheng.vo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by cheng on 2018/5/13.
 */
public class CustomRealm extends AuthorizingRealm {

    @Resource
    private UserDao userDao;

    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1、通过用户获得角色数据
        String userName = (String) principals.getPrimaryPrincipal();
        Set<String> roles = getRoleByUserName(userName);
        Set<String> permissions = getPermissionsByUserName(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1、从主体传过来的认证信息中，获得用户名
        String userName = (String) token.getPrincipal();
        //2、通过用户名到数据库中取得凭证
        String password = getPasswordByUserName(userName);
        if (password == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("cheng", password, "customRealm");
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("1991"));
        return authenticationInfo;
    }

    /**
     * 模拟从数据库中查询凭证
     *
     * @param userName
     * @return
     */
    private String getPasswordByUserName(String userName) {

        User user = userDao.getUserByUserName(userName);
        return user.getPassword();
    }

    /**
     * @param username
     * @return
     */
    private Set<String> getRoleByUserName(String username) {
        List<String> list = userDao.getRoleByUserName(username);
        Set<String> set=new HashSet<>(list);
        return set;
    }

    /**
     * 模拟从数据库中查询权限
     *
     * @param username
     * @return
     */
    private Set<String> getPermissionsByUserName(String username) {
        Set<String> sets = new HashSet<>();
        sets.add("user:delete");
        sets.add("user:insert");
        return sets;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456", "1991");
        System.out.println(md5Hash.toString());
    }

}
